"""
头像服务
处理用户头像的映射和管理
"""

import os
import json
import hashlib
from pathlib import Path
from typing import Dict, Optional

class AvatarService:
    """头像服务类"""
    
    def __init__(self):
        self.avatar_dir = "/Users/kangqing/workspace/doc_service/static/images/avatars"
        self.mapping_file = os.path.join(self.avatar_dir, "avatar_mapping.json")
        self.avatar_count = 100
        self._mapping_cache: Optional[Dict[str, str]] = None
    
    def _load_mapping(self) -> Dict[str, str]:
        """加载映射文件"""
        if self._mapping_cache is not None:
            return self._mapping_cache
        
        try:
            with open(self.mapping_file, 'r', encoding='utf-8') as f:
                self._mapping_cache = json.load(f)
            return self._mapping_cache
        except FileNotFoundError:
            # 如果映射文件不存在，返回空字典
            return {}
    
    def _generate_user_id_hash(self, user_id: str) -> int:
        """根据用户ID生成哈希值"""
        return int(hashlib.md5(user_id.encode()).hexdigest(), 16)
    
    def get_avatar_filename(self, user_id: str) -> str:
        """获取用户对应的头像文件名"""
        # 首先尝试从映射文件中获取
        mapping = self._load_mapping()
        if user_id in mapping:
            return mapping[user_id]
        
        # 如果没有映射，使用哈希值生成
        hash_value = self._generate_user_id_hash(user_id)
        avatar_index = (hash_value % self.avatar_count) + 1
        return f"avatar_{avatar_index:03d}.jpg"
    
    def get_avatar_url(self, user_id: str) -> str:
        """获取用户头像的URL"""
        avatar_filename = self.get_avatar_filename(user_id)
        return f"/static/images/avatars/{avatar_filename}"
    
    def get_avatar_path(self, user_id: str) -> str:
        """获取用户头像的文件路径"""
        avatar_filename = self.get_avatar_filename(user_id)
        return os.path.join(self.avatar_dir, avatar_filename)
    
    def avatar_exists(self, user_id: str) -> bool:
        """检查用户头像文件是否存在"""
        avatar_path = self.get_avatar_path(user_id)
        return os.path.exists(avatar_path)

# 创建全局实例
avatar_service = AvatarService()